package controller;

import logic.ILogic;
import boundary.IUI;
import entity.DALException;
import entity.IOperatorDAO;
import entity.OperatorDTO;

public class Controller {

	private IUI ui;
	private ILogic logic;
	private IOperatorDAO data;

	public void setRefs(IUI ui, ILogic logic, IOperatorDAO data){
		this.ui = ui;
		this.logic = logic;
		this.data = data;
	}

	public void start(){
		while(true){
			login();
			if(!logic.isLoggedIn())
				ui.error("Invalid credentials");
			else
				break;
		}

		while (true) {
			int selection = logic.isAdmin() ? ui.adminAction() : ui.userAction();
			
			if(selection == 0)
				break;
			
			try {
				
				if(logic.isAdmin())
					adminSelection(selection);
				else
					userSelection(selection);
				
			} catch (DALException e) {
				ui.error(e.getMessage());
			//	System.out.println("Det valgte bruger ID findes ikke i de gemte operatører");

			}
		}
	}
	
	private void login() {
		String[] loginOptions = ui.login();
		logic.login(loginOptions[0], loginOptions[1]);
	}
	
	private void adminSelection(int selection) throws DALException{
		
		switch (selection) {
		case 1: // Show operators
			ui.showOperators(data.getOperatorList());
			break;

		case 2: // Show operator
			OperatorDTO opr = data.getOperator(ui.selectUser());
			if(opr == null){
				ui.error("No Operator");
			}
			else{
				ui.showOperator(opr);
			}
			break;
			
		case 3: // Add operator
			// input: name, cpr
			OperatorDTO oprInfo = ui.createOperator();
			ui.showOperator(data.createOperator(oprInfo));
			break;

		case 4: // Update operator
			// input: userID, name, cpr, password
			int oprId = ui.selectUser();
			OperatorDTO uOpr = data.getOperator(oprId);
			if(uOpr == null){
				ui.error("No Operator");
			}
			else{
				OperatorDTO oprUInfo = ui.updateOperator(uOpr);
				
				data.updateOperator(oprUInfo);
				ui.success("Operator updated");
				ui.showOperator(data.getOperator(oprId));
			}
			break;
			
		case 5: // Delete operator
			data.deleteOperator(ui.selectUser());
			break;
		}		
	}
	private void userSelection(int selection) throws DALException{
		
		switch (selection) {
		case 1: // Change password			
			String[] passwords = ui.changePassword();
	
			logic.changePassword(passwords);
			ui.success("Password has been changed.");
			break;
			
		case 2: // Weight application
			double[] weight = ui.weightApp();
			double netWeight = logic.calculateNetWeight(weight[0], weight[1]);
			ui.showNetWeight(netWeight);
			break;
		}
	}
}
